import { RESPONSE_CODE, STORE_KEY } from '@/common/config';
import { handleBindMobilePhone, handleEditMobilePhone, handleShopChannelCategories, handleShopUserprofileEditSingle, handleShopUserprofileInfo, handleShopUserSetting } from '@/common/service';
import { handleInitStoreBaseInfo, handleLoginCallback, showToast } from '@/common/util';
import { IBindPhone, IBindPhonePromise, IChannelCategories, IChannelCategoriesItem, IResponseSuccess, IUserProfileEditPromise, IUserProfileInfo, IUserProfileInfoData, IUserProfileSingleEdit, IUserSetting, IUserSettingPromise, USER_PROFILE_STATUS } from '@/typing';
import Taro from '@tarojs/taro';


import { useState } from 'react';

const useProfileInfoAction = () => {
    const [userProfileInfoData, setUserProfileInfoData] = useState<IUserProfileInfoData | undefined>(undefined);



    const handleInitProfileInfo = async () => {
        return new Promise(async (resolve) => {
            try {
                const { data: { code, data,msg } } = await handleShopUserprofileInfo() as IResponseSuccess<IUserProfileInfo>;

                if (code === RESPONSE_CODE.SUCCESS) {
                    setUserProfileInfoData(data);
                    resolve({
                        code,
                        data
                    });
                } else if (code === RESPONSE_CODE.LOGIN_EXPIRE || code === RESPONSE_CODE.LOGIN_NEED) {
                    handleLoginCallback(() => handleInitProfileInfo())
                    //  Taro.removeStorageSync(STORE_KEY.PHONE)
                    // await handleInitLogin().then(async () => {
                    //     handleInitProfileInfo()
                    // })
                } else if (code === RESPONSE_CODE.ERROR) {
                    throw new Error("请求异常");

                }else{
                    showToast(msg)
                }
            } catch (error) {
                showToast('请求失败，请重试')


                console.error('Error fetching profile info:', error);
            }
        })

    };
    const handleInitStoreProfileInfo = () => {
        Taro.removeStorageSync(STORE_KEY.BASE_USER_INFO)
        const storeBaseUserInfo = handleInitStoreBaseInfo();
        handleInitProfileInfo().then((profileInfoData: IUserProfileInfo) => {
            const{code,data} = profileInfoData
            if (code === RESPONSE_CODE.SUCCESS) {
                const { avatar, city_code, district_code, topic, gender, introduction, media_img, media_video, nickname, province_code, readme, job_type, modify_field, status, service_type } = data
            const jobIdList = job_type.map((item) => item.job_type_id);
            const jobIdDesc = job_type.map((item) => item.name);
           
            const serviceTypeIdList = service_type.map((item) => item.service_type_id);
            const serviceTypeDescList = service_type.map((item) => item.name);
            storeBaseUserInfo['job_type'] = jobIdList;
            storeBaseUserInfo['avatar'] = avatar;
            storeBaseUserInfo['gender'] = gender;
            storeBaseUserInfo['nickname'] = nickname;
            storeBaseUserInfo['introduction'] = introduction;
            storeBaseUserInfo['province_code'] = province_code;
            storeBaseUserInfo['city_code'] = city_code;
            storeBaseUserInfo['district_code'] = district_code;
            // storeBaseUserInfo['district_code'] = district_code;

            if (status === USER_PROFILE_STATUS.enable) {
                storeBaseUserInfo['modify_field'] = modify_field;

            }

            Taro.setStorageSync(STORE_KEY.BASE_USER_INFO, JSON.stringify(storeBaseUserInfo))
            Taro.setStorageSync(STORE_KEY.JOB_ID_LIST, JSON.stringify(jobIdList))
            Taro.setStorageSync(STORE_KEY.JOB_ID_DESC, JSON.stringify(jobIdDesc))
            Taro.setStorageSync(STORE_KEY.ADD_SERVICE_TYPE, JSON.stringify(serviceTypeIdList))
            Taro.setStorageSync(STORE_KEY.ADD_SERVICE_TYPE_DESC, JSON.stringify(serviceTypeDescList))
            Taro.setStorageSync(STORE_KEY.TOPIC, JSON.stringify(topic))
            Taro.setStorageSync(STORE_KEY.README, readme)
            if (media_img && media_img.length > 0) {
                Taro.setStorageSync(STORE_KEY.PHOTO_LIST, JSON.stringify(media_img))
                Taro.setStorageSync(STORE_KEY.ORIGIN_PHOTO_LIST, JSON.stringify(media_img))

            }
            if (media_video) {
                Taro.setStorageSync(STORE_KEY.VIDEO_URL, media_video)
            }
            }
            

        })

    }

    const handleInitJobInfo = async (): Promise<Array<IChannelCategoriesItem>> => {
        return new Promise(async (resolve) => {
            try {
                const { data: { code, data } } = await handleShopChannelCategories() as IResponseSuccess<IChannelCategories>;

                if (code === RESPONSE_CODE.SUCCESS) {

                    resolve(data);
                } else if (code === RESPONSE_CODE.ERROR) {
                    throw new Error("请求异常");

                }
            } catch (error) {
                showToast('请求失败，请重试')


                console.error('Error fetching profile info:', error);
            }
        })

    }
    const handleShopUserprofileEdit = async (editData): Promise<IUserProfileEditPromise> => {
        return new Promise(async (resolve) => {
            Taro.showLoading({
                title: '修改中...',
                mask: true,
            })
            const editRes= await handleShopUserprofileEditSingle(editData) as IResponseSuccess<IUserProfileSingleEdit>;
            console.log(editRes)
            if(editRes.statusCode===RESPONSE_CODE.AJAX_SUCCESS){
                const {code,msg,data} =editRes.data
                resolve({
                    code,
                    msg,
                    data
                })
            }else {
                showToast('请求失败，请重试')

            }
            
        })

    }
    const handleBindMobilePhoneAjax = (phone): Promise<IBindPhonePromise> => {
        return new Promise(async (resolve) => {
            try {
                Taro.showLoading({
                    title: '',

                    mask: true
                })
                const { data: { code, data, msg } } = await handleBindMobilePhone(phone) as IResponseSuccess<IBindPhone>;
                let mobile = ''

                Taro.hideLoading();
                if (code === RESPONSE_CODE.SUCCESS) {
                    mobile = data?.mobile || ''
                }
                resolve({
                    code,
                    mobile,
                    msg
                })

            } catch (error) {
                Taro.hideLoading();
                showToast('请求失败，请重试')

            }
        })
    }
    const handleEditMobilePhoneAjax = (phone): Promise<IBindPhonePromise> => {
        return new Promise(async (resolve) => {
            try {
                Taro.showLoading({
                    title: '',

                    mask: true
                })
                const { data: { code, data, msg } } = await handleEditMobilePhone(phone) as IResponseSuccess<IBindPhone>;
                let mobile = ''

                Taro.hideLoading();
                if (code === RESPONSE_CODE.SUCCESS) {
                    mobile = data?.mobile || ''
                }
                resolve({
                    code,
                    mobile,
                    msg
                })

            } catch (error) {
                Taro.hideLoading();
                showToast('请求失败，请重试')

            }
        })
    }

    const handleUserSettingAjax = (): Promise<IUserSettingPromise> => {
        return new Promise(async (resolve) => {
            try {
                Taro.showLoading({
                    title: '',

                    mask: true
                })
                const { data: { code, data, msg } } = await handleShopUserSetting() as IResponseSuccess<IUserSetting>;

                Taro.hideLoading();

                resolve({
                    code,
                    ...data,
                    msg,
                })

            } catch (error) {
                Taro.hideLoading();
                showToast('请求失败，请重试')

            }
        })
    }



    return {
        userProfileInfoData,
        handleInitProfileInfo,
        handleInitStoreProfileInfo,
        handleShopUserprofileEdit,
        handleInitJobInfo,
        handleBindMobilePhoneAjax,
        handleEditMobilePhoneAjax,
        handleUserSettingAjax

    };
};

export default useProfileInfoAction;
